
import 'package:flutter/material.dart';
import 'package:syria_sports/core/utils/show_toast.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:collection/collection.dart';

import '../../../core/app_export.dart';
import '../../../data/apiClient/apis_data.dart';
import '../../../widgets/app_bar/appbar_subtitle.dart';
import '../../../widgets/app_bar/custom_app_bar.dart';
import '../../../widgets/app_bar/outline_icon_button.dart';
import '../../../widgets/custom_elevated_button.dart';
import '../../admin_home_tabs/cp_tab/models/home_model.dart';
import '../bloc/attendances_list_screen.dart';
import '../widgets/date_range_picker_widget.dart';



class TableRangeExample extends StatefulWidget {
  const TableRangeExample({super.key});

  @override
  State<TableRangeExample> createState() => _TableRangeExampleState();
}

class _TableRangeExampleState extends State<TableRangeExample>{

  final CalendarFormat _calendarFormat = CalendarFormat.month;
  RangeSelectionMode _rangeSelectionMode = RangeSelectionMode.toggledOn;
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;
  DateTime? _rangeStart;
  DateTime? _rangeEnd;
  bool isLoading = false;
  FluffyGym? _selectedGym;
  GymExercise? _selectedExercise;

  @override
  void initState() {
    // TODO: implement initState
    _selectedGym = APISData.homeData.gyms.firstWhereOrNull((element) => element.gymId == _selectedGym?.gymId);
    _selectedExercise = _selectedGym?.exercises.firstWhereOrNull((element) => element.exerciseId == _selectedExercise?.exerciseId);

    _rangeStart = DateTime.now();
    _rangeEnd = DateTime.now();

    //updateHomeData();
    super.initState();
  }

/*  updateHomeData()async{
    if(isLoading)return;

    setState(() {
      isLoading= true;
    });
    await APISData.cpCubit.getHomeData();
    _selectedGym = APISData.homeData.gyms.firstWhereOrNull((element) => element.gymId == _selectedGym?.gymId);
    _selectedExercise = _selectedGym?.exercises.firstWhereOrNull((element) => element.exerciseId == _selectedExercise?.exerciseId);


    setState(() {
      isLoading= false;
    });
  }*/


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:_buildAppBar(context:context ),
      body: Column(
        children: [
          if(isLoading)
            const LinearProgressIndicator(backgroundColor: Colors.black54),
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  TableCalendar(
                    locale: 'ar_SA',
                    firstDay: DateTime.utc(1999),
                    lastDay: DateTime.utc(3000),
                    focusedDay: _focusedDay,
                    selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
                    rangeStartDay: _rangeStart,
                    rangeEndDay: _rangeEnd,
                    calendarFormat: _calendarFormat,
                    rangeSelectionMode: _rangeSelectionMode,
                    daysOfWeekStyle: const DaysOfWeekStyle(
                      weekdayStyle: TextStyle(color: Colors.orange,fontSize: 12),
                      weekendStyle: TextStyle(color: Colors.red,fontSize: 12),

                    ),
                    onDaySelected: (selectedDay, focusedDay) {
                      if (!isSameDay(_selectedDay, selectedDay)) {
                        setState(() {
                          _selectedDay = selectedDay;
                          _focusedDay = focusedDay;
                          _rangeStart = null; // Important to clean those
                          _rangeEnd = null;
                          _rangeSelectionMode = RangeSelectionMode.toggledOff;
                        });
                      }
                    },
                    headerStyle: HeaderStyle(
                      titleTextStyle:theme.textTheme.titleMedium??const TextStyle(),
                      //formatButtonTextStyle: TextStyle(color: Colors.white),
                      formatButtonVisible: false,
                      titleCentered: true,
                      leftChevronIcon: Icon(Icons.chevron_left,color: theme.textTheme.titleMedium?.color,),
                      rightChevronIcon: Icon(Icons.chevron_right,color: theme.textTheme.titleMedium?.color,),
                    ),

                    onRangeSelected: (start, end, focusedDay) {
                      setState(() {
                        _selectedDay = null;
                        _focusedDay = focusedDay;
                        _rangeStart = start;
                        _rangeEnd = end;
                        _rangeSelectionMode = RangeSelectionMode.toggledOn;
                      });
                    },

                    onPageChanged: (focusedDay) {
                      _focusedDay = focusedDay;
                    },
                    weekendDays: const [DateTime.friday],
                    calendarStyle: CalendarStyle(
                      defaultTextStyle: theme.textTheme.titleMedium??const TextStyle(),
                      weekendTextStyle: theme.textTheme.titleMedium??const TextStyle(),
                      todayTextStyle:TextStyle(color: Colors.black),
                      holidayTextStyle: theme.textTheme.titleMedium??const TextStyle(),
                      rangeHighlightColor: theme.textTheme.titleMedium?.color?.withOpacity(.1)??Colors.black26,
                      withinRangeTextStyle: TextStyle(color: Colors.orange),
                      rangeStartDecoration: BoxDecoration(color: Colors.red,shape: BoxShape.circle),
                      rangeEndDecoration: BoxDecoration(color: Colors.red,shape: BoxShape.circle),
                      disabledTextStyle: theme.textTheme.titleMedium??const TextStyle(),

                      todayDecoration: BoxDecoration(
                        color: Colors.orangeAccent,
                        shape: BoxShape.circle,
                      ),
                      selectedDecoration: BoxDecoration(
                        color: Colors.red,
                        shape: BoxShape.rectangle,
                      ),
                      selectedTextStyle: theme.textTheme.titleMedium??const TextStyle(),
                    ),
                  ),
                  DateRangePickerWidget(startDate: _rangeStart,endDate: _rangeEnd,),
                  Align(
                    alignment: Alignment.centerRight,
                    child: Padding(
                      padding: const EdgeInsets.all(4.0),
                      child: Text('النادي:',style: theme.textTheme.bodySmall!.copyWith(fontSize: 16),),
                    ),
                  ),
                  DropdownButton<FluffyGym>(
                    value: _selectedGym,
                    dropdownColor: Theme.of(context).colorScheme.secondary,
                    isExpanded: true,
                    hint: Text('اختر نادي',style: theme.textTheme.titleSmall,),
                    onChanged: (value) {
                      setState(() {
                        _selectedGym = value;
                        _selectedExercise = null;

                      });
                    },
                    items: List.generate(APISData.homeData.gyms.length+1, (index) {
                      if(index == 0){
                        return DropdownMenuItem(
                          value: null,
                          child: Text('الكل',style: theme.textTheme.titleSmall!.copyWith(color: Colors.orange),),
                        );
                      }else {
                        return DropdownMenuItem(
                      value: APISData.homeData.gyms[index-1],
                      child: Text(APISData.homeData.gyms[index-1].name,style: theme.textTheme.titleSmall!.copyWith(color: Colors.orange),),
                    );
                      }
                    },
                    ),
                  ),
                  if(_selectedGym != null)
                  Column(
                    children: [
                      const SizedBox(height: 8),
                      Align(
                        alignment: Alignment.centerRight,
                        child: Padding(
                          padding: const EdgeInsets.all(4.0),
                          child: Text('التمرين:',style: theme.textTheme.bodySmall!.copyWith(fontSize: 16),),
                        ),
                      ),
                      DropdownButton<GymExercise>(
                        value: _selectedExercise,
                        dropdownColor: Theme.of(context).colorScheme.secondary,
                        isExpanded: true,
                        hint: Text('اختر التمرين',style: theme.textTheme.titleSmall,),
                        onChanged: (value) {
                          setState(() {
                            _selectedExercise = value;
                          });
                        },
                        items:(_selectedGym==null)?[]:List.generate(_selectedGym!.exercises.length, (index) =>
                            DropdownMenuItem(
                              value: _selectedGym!.exercises[index],
                              child: Text(_selectedGym!.exercises[index].name,style: theme.textTheme.titleSmall!.copyWith(color: Colors.orange),),
                            ),
                        ),
                      ),
                    ],
                  ),

                  CustomElevatedButton(
                      height: 45,
                      text:"عرض",
                      rightIcon: Icon(Icons.search,color: theme.textTheme.titleMedium?.color,),
                      buttonTextStyle: CustomTextStyles.titleSmallOnPrimaryContainer,
                      margin:const EdgeInsets.all(16),
                      onPressed: () {
                        if(_selectedExercise == null && _selectedGym != null){
                          showErrorMessage(message: 'الرجاء تحديد تمرين اولاً');
                          return;
                        }
                         Navigator.push(context, MaterialPageRoute(builder: (context) => AttendancesListScreen(
                           endDate: _rangeEnd??DateTime.now(),
                           startDate: _rangeStart??DateTime.now(),
                           exerciseId: _selectedExercise?.exerciseId,
                         )));

                      }),
                  const SizedBox(height: 16),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
  PreferredSizeWidget _buildAppBar({required BuildContext context}) {
    return CustomAppBar(
      leading: OutlineIconButton(
        imagePath: ImageConstant.imgRightIcon,
        onTapped: (){
          Navigator.pop(context);
        },
      ),

      title: AppbarSubtitle(text: 'حدد تاريخ وتمرين للمتابعة'),
      actions: [
        /*IconButton(
          icon:const Icon(Icons.refresh),
          onPressed: (){
            updateHomeData();
          },
        ),*/
      ],
    );
  }
}